import { useState, useCallback } from 'react';
import { freemarkerAPI } from '@/services/toolService';

/**
 * Freemarker工具的自定义Hook
 * 管理Freemarker模板处理的状态和逻辑
 */
export const useFreemarker = () => {
    // 状态管理
    const [ftl, setFtl] = useState('');
    const [json, setJson] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');
    const [result, setResult] = useState('');
    const [copySuccess, setCopySuccess] = useState(false);

    /**
     * 提交并处理Freemarker模板
     */
    const handleSubmit = useCallback(async () => {
        if (!ftl.trim() || isLoading) return;

        setIsLoading(true);
        setError('');
        setResult('');
        setCopySuccess(false);

        try {
            // 验证JSON格式
            let jsonData = json.trim();
            if (jsonData) {
                try {
                    JSON.parse(jsonData);
                } catch (jsonError) {
                    throw new Error("JSON 数据格式不正确");
                }
            }

            const data = await freemarkerAPI(ftl, json);
            setResult(data);
        } catch (err) {
            setError(err instanceof Error ? err.message : "请求错误，请稍后重试");
        } finally {
            setIsLoading(false);
        }
    }, [ftl, json, isLoading]);

    /**
     * 复制结果到剪贴板
     */
    const copyToClipboard = useCallback(() => {
        if (!result) return;

        navigator.clipboard.writeText(result)
            .then(() => {
                setCopySuccess(true);
                setTimeout(() => setCopySuccess(false), 2000);
            })
            .catch(() => setError("复制失败"));
    }, [result]);

    /**
     * 加载示例模板和数据
     */
    const loadExample = useCallback(() => {
        setFtl(`<!DOCTYPE html>
<html>
<head>
    <title>FreeMarker 示例</title>
</head>
<body>
    <h1>你好, \${user.name}</h1>
    <p>你的年龄是: \${user.age}</p>
    
    <h2>字符串函数示例:</h2>
    <ul>
        <li>首字母大写: \${user.name?cap_first}</li>
        <li>全部大写: \${user.name?upper_case}</li>
        <li>字符串长度: \${user.name?length}</li>
    </ul>
    
    <h2>集合函数示例:</h2>
    <p>你有 \${user.hobbies?size} 个兴趣爱好:</p>
    <ul>
    <#list user.hobbies as hobby>
        <li>\${hobby}</li>
    </#list>
    </ul>
</body>
</html>`);

        setJson(`{
  "user": {
    "name": "zhang san",
    "age": 28,
    "hobbies": ["阅读", "编程", "旅行"]
  }
}`);
    }, []);

    /**
     * 清除错误信息
     */
    const clearError = useCallback(() => {
        setError('');
    }, []);

    return {
        // 状态
        ftl,
        json,
        isLoading,
        error,
        result,
        copySuccess,
        // 设置函数
        setFtl,
        setJson,
        // 操作函数
        handleSubmit,
        copyToClipboard,
        loadExample,
        clearError
    };
};